//
//  DetailViewController.m
//  Final
//
//  Created by Lenrony on 2021/12/2.
//  Copyright © 2021 Lenrony. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "DetailViewController.h"

@interface DetailViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextViewDelegate>{
    
    int imgtypes[9];//图片类型
    float screen_width;
    float screen_height;
    float comment_height;
}

@property(strong, nonatomic) Article* article;
@property(strong, nonatomic) NSMutableArray* comments;
@property(nonatomic) int numSupports;
@property(strong, nonatomic) ModelController* mc;
@property(strong, nonatomic) NSMutableArray* fieldArr;

@property(strong, nonatomic) UIScrollView* scrollView;
@property(strong, nonatomic) RawUserView* ruv;
@property(strong, nonatomic) UILabel* articleLabel;

@property(strong, nonatomic) UICollectionView* imgcv;//九宫格View
@property(strong, nonatomic) UIImageView* bgv;      //放大显示的图片View
@property(strong, nonatomic) UIImageView* circle;   //放大显示的视频播放按钮
@property(strong, nonatomic) UIGestureRecognizer* tapGesture;//退出放大显示的图片点击手势

@property(nonatomic) int showingImgIndex;//当前被放大的图片/视频
@property(strong, nonatomic) AVPlayer* avPlayer;//视频播放器
@property(strong, nonatomic) AVPlayerViewController* avPlayerVC;//视频播放页面

@property(strong, nonatomic) NSMutableArray* imgurls;//图片或视频的url

@property(strong, nonatomic) UILabel* timeLabel;
@property(strong, nonatomic) UILabel* typeLabel;
@property(strong, nonatomic) UILabel* commentLabel;

@property(strong, nonatomic) UIView* artBackView;
@property(strong, nonatomic) UIButton* supportBtn;
@property(nonatomic) BOOL isClicked;
@property(strong, nonatomic) UIImageView* subiv;
@property(strong, nonatomic) UIImage* notSupportImg;
@property(strong, nonatomic) UIImage* yesSupportImg;

@property(strong, nonatomic) UIButton* commentBtn;
@property(strong, nonatomic) UIView* bouncedView;
@property(strong, nonatomic) UITextView* ctv;
@property(strong, nonatomic) UIButton* postCommentBtn;
@property(strong, nonatomic) UIGestureRecognizer* exitEditingGesture;

@property(strong, nonatomic) CommentView* cv;

@property(strong, nonatomic) UIAlertController* alert;

@end

@implementation DetailViewController

-(DetailViewController*) initWithArticle: (Article*)article
{
    self = [super init];
    screen_width = [UIScreen mainScreen].bounds.size.width;
    screen_height = [UIScreen mainScreen].bounds.size.height;
    self.mc = [ModelController getInstance];
    self.fieldArr = [[NSMutableArray alloc]initWithObjects:@"二手闲置", @"打听求助",@"青青子衿",@"瓜田趣事",@"校园招聘",nil];
    
    self.article = article;
    return self;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    self.numSupports = [self.mc getSupportWithAID:self.article.a_id];
    self.imgurls = self.article.images;
    for(int i = 0; i < self.imgurls.count; i++){
        imgtypes[i] = [self.article.images_type[i] intValue];
    }
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
    self.scrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"gray.png"]];
    
    RawUser* hostRu = [self.mc getRawUser:self.article.u_id];
    self.ruv = [[RawUserView alloc]initWithRawUser:hostRu andViewController:self];
    self.ruv.frame = CGRectMake(0, 0, screen_width / 2, 40);
    [self.scrollView addSubview:self.ruv];
    
    self.articleLabel = [[UILabel alloc]init];
    self.articleLabel.text = self.article.content;
    self.articleLabel.font = [UIFont systemFontOfSize:18];
    self.articleLabel.numberOfLines = 0;
    self.articleLabel.textAlignment = NSTextAlignmentLeft;
    CGSize size = [self.article.content boundingRectWithSize:CGSizeMake(screen_width - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.articleLabel.font} context:nil].size;
    [self.articleLabel setFrame:CGRectMake(10, 50, size.width, size.height)];
    [self.scrollView addSubview:self.articleLabel];
    
    [self loadImgCollectionViews];
    
    [self.scrollView addSubview:self.timeLabel];
    [self.scrollView addSubview:self.typeLabel];
    [self.scrollView addSubview:self.supportBtn];
    [self.scrollView addSubview:self.commentLabel];
    [self.scrollView addSubview:self.commentBtn];
    
    self.notSupportImg = [UIImage imageNamed:@"dianzan.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    self.yesSupportImg = [UIImage imageNamed:@"dianzan-2.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    if(self.numSupports < 0){
        self.numSupports = -self.numSupports;
        self.isClicked = true;
        self.subiv.image = self.yesSupportImg;
    }
    else{
        self.isClicked = false;
        self.subiv.image = self.notSupportImg;
    }
    [self.supportBtn setTitle:[NSString stringWithFormat:@"     %d", self.numSupports] forState:UIControlStateNormal];
    
    [self loadCommentView];
    
    self.artBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width, self.supportBtn.frame.origin.y + self.supportBtn.frame.size.height + 5)];
    self.artBackView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.artBackView];
    [self.scrollView sendSubviewToBack:self.artBackView];
    
    [self.view addSubview:self.scrollView];
    self.scrollView.scrollEnabled = YES;
    self.scrollView.userInteractionEnabled = YES;
    self.scrollView.showsVerticalScrollIndicator = YES;
    
    [self.view addSubview:self.bouncedView];
    self.exitEditingGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(exitEditingAction)];
    
    [self.view addSubview:self.bgv];
}

-(void)loadCommentView
{
    comment_height = 0;
    self.comments = [self.mc getCommentWithAID:self.article.a_id];
    NSMutableArray* rawusers = [[NSMutableArray alloc]init];
    NSMutableArray* contents = [[NSMutableArray alloc]init];
    NSMutableArray* timestamps = [[NSMutableArray alloc]init];
    for(int i = 0; i < self.comments.count; i++){
        Comment* com = self.comments[i];
        RawUser* ru = [self.mc getRawUser: com.u_id];
        [rawusers addObject:ru];
        [contents addObject:com.content];
        [timestamps addObject:com.time_stamp];
        CGSize size = [com.content boundingRectWithSize:CGSizeMake(screen_width - 10, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]} context:nil].size;
        size = CGSizeMake(screen_width - 10, size.height + 55);
        comment_height += size.height;
    }
    if(self.cv != nil){
        [self.cv removeFromSuperview];
    }
    self.cv = [[CommentView alloc]initWithRawUsers:rawusers andContents:contents andTimes:timestamps andViewController:self];
    float y = self.commentLabel.frame.origin.y + self.commentLabel.bounds.size.height + 15;
    self.cv.frame = CGRectMake(0, y, screen_width, comment_height);
    [self.scrollView addSubview:self.cv];
    self.scrollView.contentSize = CGSizeMake(screen_width, y + comment_height + 150);
}

-(void)loadImgCollectionViews
{
    //起初没有图片被展示
    self.showingImgIndex = -1;
    float y = self.articleLabel.bounds.size.height + 60;
    
    //九宫格中每一个格子布局
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((screen_width - 40) / 3, (screen_width - 40) / 3);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    
    //九宫格布局
    int imgcount = (int)(self.imgurls.count + 2) / 3;
    self.imgcv = [[UICollectionView alloc]initWithFrame:CGRectMake(0, y, screen_width, screen_width * imgcount / 3) collectionViewLayout:layout];
    self.imgcv.backgroundColor = [UIColor clearColor];
    self.imgcv.scrollEnabled = NO;
    self.imgcv.userInteractionEnabled = YES;//起初允许交互
    
    //设置代理、注册
    self.imgcv.delegate = self;
    self.imgcv.dataSource = self;
    [self.imgcv registerClass:[ImgCell class] forCellWithReuseIdentifier:@"NineImgs"];
    [self.scrollView addSubview: self.imgcv];
    
    //放大展示到图片
    self.bgv = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width / 2, screen_height / 2, 0, 0)];
    self.bgv.backgroundColor = [UIColor blackColor];
    self.bgv.contentMode = UIViewContentModeScaleAspectFit;
    
    //手势
    self.tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    
    //放大显示的视频播放按钮
    UIImage* playerIcon = [UIImage imageNamed:@"bofang.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    self.circle = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width / 2 - 50, screen_height / 2 - 50, 100, 100)];
    self.circle.center = self.bgv.center;
    self.circle.layer.cornerRadius = 50;
    self.circle.image = playerIcon;
    self.circle.backgroundColor = [UIColor lightGrayColor];
    [self.circle setUserInteractionEnabled:YES];
    UIGestureRecognizer* clickCircle = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playVideo)];
    [self.circle addGestureRecognizer:clickCircle];
}

//告诉代理返回的cell是什么样子的
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImgCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NineImgs" forIndexPath:indexPath];
    int ind = (int)indexPath.row;
    [cell setImgWithURL:self.imgurls[ind] andType: imgtypes[ind]];
    
    return cell;
}

//一共几个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imgurls.count;
}

//选中事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImgCell* cell = (ImgCell*)[collectionView cellForItemAtIndexPath:indexPath];
    self.bgv.image = cell.img;
    self.imgcv.userInteractionEnabled = false;//让九宫格不可交互
    int ind = (int)indexPath.row;
    
    //弹出放大展示页面
    [UIView animateWithDuration:0.2 animations:^{
        self.bgv.frame = CGRectMake(0, 0, self->screen_width, self->screen_height);
        self.bgv.alpha = 1;
    } completion:^(BOOL finished) {
        //动画结束后，如果是视频，需要添加播放按钮
        if(self->imgtypes[ind] == 1){
            [self.bgv addSubview:self.circle];
        }
    }];
    
    self.bgv.userInteractionEnabled = true;//展示界面允许交互
    [self.bgv addGestureRecognizer:self.tapGesture];//可以点击退出
    self.showingImgIndex = ind;//当前展示的id
}

-(void)tapAction
{
    self.imgcv.userInteractionEnabled = true;//让九宫格可以交互
    
    //消失展示界面
    [UIView animateWithDuration:0.2 animations:^{
        self.bgv.frame = CGRectMake(self->screen_width / 2, self->screen_height / 2, 0, 0);
        self.bgv.alpha = 0;
        [self.circle removeFromSuperview];
    }];
    
    self.bgv.userInteractionEnabled = false;//展示界面禁止交互
    [self.bgv removeGestureRecognizer:self.tapGesture];//取消手势
    self.showingImgIndex = -1;
}

//播放视频
-(void)playVideo
{
    //获取视频，优先从本地获取
    NSString* urlStr = self.imgurls[self.showingImgIndex];
    NSString* filePath = [self.mc loadVideoFromCache:urlStr];
    NSURL* url;
    if(filePath != nil){
        url = [NSURL fileURLWithPath:filePath];
    }
    else{
        url = [NSURL URLWithString:urlStr];
    }
    
    //打开视频播放界面开始播放
    self.avPlayer = [[AVPlayer alloc]initWithURL:url];
    self.avPlayerVC = [[AVPlayerViewController alloc]init];
    self.avPlayerVC.player = self.avPlayer;
    [self presentViewController:self.avPlayerVC animated:YES completion:nil];
    [self.avPlayer play];
}

-(void)supportClicked
{
    if(self.isClicked){
        return;
    }
    if(self.mc.cur_user == nil){
        [self showAlertWithTitle:@"点赞失败" andText:@"请先登录"];
        return;
    }
    
    int ret = [self.mc support:self.article.a_id];
    if(ret == 0){
        self.isClicked = true;
        self.subiv.image = self.yesSupportImg;
        [self.supportBtn setTitle:[NSString stringWithFormat:@"     %d", self.numSupports + 1] forState:UIControlStateNormal];
    }
    else{
        [self showAlertWithTitle:@"点赞失败" andText:@"网络连接异常！"];
    }
    
}


-(void)commentClicked
{
    if(self.mc.cur_user == nil){
        [self showAlertWithTitle:@"评论失败" andText:@"请先登录"];
        return;
    }
    NSLog(@"Comment");
    [UIView animateWithDuration:0.5 animations:^{
        [self.bouncedView setFrame:CGRectMake(0, self->screen_height - 250, self->screen_width, 250)];
    } completion:^(BOOL finished) {
        [self.scrollView addGestureRecognizer:self.exitEditingGesture];
    }];
}

- (void)showAlertWithTitle: (NSString*)title
                   andText: (NSString*)text
{
    self.alert = [UIAlertController alertControllerWithTitle:title message:text preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:self.alert animated:YES completion:nil];
    [self performSelector:@selector(hideAlert) withObject:self.alert afterDelay:1.5];
}

- (void)hideAlert
{
    [self.alert dismissViewControllerAnimated:YES completion:nil];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.text = @"请输入评论";
        textView.textColor = [UIColor grayColor];
    }
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"请输入评论"]){
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}

-(void)postComment
{
    NSString* content = self.ctv.text;
    if([content isEqualToString:@""] || ([content isEqualToString:@"请输入评论"] && [self.ctv.textColor isEqual:[UIColor grayColor]])){
        [self showAlertWithTitle:@"评论失败" andText:@"评论内容不能为空！"];
        return;
    }
    
    int ret = [self.mc comment:self.article.a_id with:content];
    if(ret == 0){
        [self showAlertWithTitle:@"评论成功" andText:@""];
        [self loadCommentView];
        [self exitEditingAction];
    }
    else{
        [self showAlertWithTitle:@"评论失败" andText:@"网络连接异常！"];
    }
}

-(void)exitEditingAction
{
    [UIView animateWithDuration:0.5 animations:^{
        [self.bouncedView setFrame:CGRectMake(0, self->screen_height, self->screen_width, 250)];
    } completion:^(BOOL finished) {
        [self.scrollView removeGestureRecognizer:self.exitEditingGesture];
    }];
}

//LazyLoad
-(UILabel*)timeLabel
{
    if(_timeLabel == nil){
        _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(screen_width / 2, 10, screen_width / 2 - 10, 20)];
        _timeLabel.text = self.article.time_stamp;
        _timeLabel.textColor = [UIColor grayColor];
        _timeLabel.textAlignment = NSTextAlignmentRight;
        [_timeLabel setFont:[UIFont systemFontOfSize:16]];
    }
    return _timeLabel;
}

-(UILabel*)typeLabel
{
    if(_typeLabel == nil){
        float y = self.imgcv.frame.origin.y + self.imgcv.bounds.size.height + 10;
        _typeLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, y, 120, 20)];
        NSString* text = [NSString stringWithFormat: @"#%@#", self.fieldArr[self.article.field - 1]];
        _typeLabel.text = text;
        _typeLabel.textColor = [UIColor blueColor];
    }
    return _typeLabel;
}

-(UIButton*)supportBtn
{
    if(_supportBtn == nil){
        float y = self.imgcv.frame.origin.y + self.imgcv.bounds.size.height + 10;
        _supportBtn = [[UIButton alloc]initWithFrame:CGRectMake(screen_width - 80, y, 70, 20)];
        [_supportBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _subiv = [[UIImageView alloc]initWithFrame:CGRectMake(5, 0, 20, 20)];
        _subiv.contentMode = UIViewContentModeScaleAspectFit;
        _subiv.clipsToBounds = YES;
        [_supportBtn addSubview:_subiv];
        
        [_supportBtn addTarget:self action:@selector(supportClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _supportBtn;
}

-(UILabel*)commentLabel
{
    if(_commentLabel == nil){
        float y = self.imgcv.frame.origin.y + self.imgcv.bounds.size.height + 50;
        _commentLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, y, 120, 20)];
        _commentLabel.text = @"评论留言";
    }
    return _commentLabel;
}

-(UIButton*)commentBtn
{
    if(_commentBtn == nil){
        float y = self.imgcv.frame.origin.y + self.imgcv.bounds.size.height + 50;
        _commentBtn = [[UIButton alloc]initWithFrame:CGRectMake(screen_width - 110, y, 100, 20)];
        [_commentBtn setTitle:@"我要评论>" forState:UIControlStateNormal];
        [_commentBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_commentBtn addTarget:self action:@selector(commentClicked) forControlEvents:(UIControlEvents)UIControlEventTouchUpInside];
    }
    return _commentBtn;
}

-(UIView*)bouncedView
{
    if(_bouncedView == nil){
        _bouncedView = [[UIView alloc]initWithFrame:CGRectMake(0, screen_height, screen_width, 250)];
        [_bouncedView addSubview:self.ctv];
        [_bouncedView addSubview:self.postCommentBtn];
        _bouncedView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
        _bouncedView.userInteractionEnabled = YES;
    }
    return _bouncedView;
}

-(UITextView*)ctv
{
    if(_ctv == nil){
        _ctv = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, screen_width - 80, 230)];
        _ctv.layer.borderColor = [UIColor grayColor].CGColor;
        _ctv.layer.cornerRadius = 8;
        _ctv.text = @"请输入评论";
        [_ctv setFont:[UIFont systemFontOfSize:18]];
        _ctv.textColor = [UIColor grayColor];
        _ctv.delegate = self;
    }
    return _ctv;
}

-(UIButton*)postCommentBtn
{
    if(_postCommentBtn == nil){
        _postCommentBtn = [[UIButton alloc]initWithFrame:CGRectMake(screen_width - 60, 20, 50, 30)];
        _postCommentBtn.backgroundColor = [UIColor colorWithRed:0 green:0.7f blue:0 alpha:1];
        _postCommentBtn.layer.cornerRadius = 5;
        [_postCommentBtn setTitle:@"提交" forState:UIControlStateNormal];
        [_postCommentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_postCommentBtn addTarget:self action:@selector(postComment) forControlEvents:UIControlEventTouchUpInside];
    }
    return _postCommentBtn;
}

@end
